<template>
  <div class="blog-detail-view">
    <el-card v-loading="loading">
      <template v-if="blog">
        <div class="blog-header">
          <h1 class="title">{{ blog.title }}</h1>
          <div class="meta">
            <el-tag size="small">{{ blog.category }}</el-tag>
            <span class="time">
              <el-icon><Calendar /></el-icon>
              {{ formatDate(blog.createTime) }}
            </span>
            <span class="author">
              <el-icon><User /></el-icon>
              {{ blog.author }}
            </span>
            <span class="views">
              <el-icon><View /></el-icon>
              {{ formatNumber(blog.viewCount) }} 阅读
            </span>
          </div>
        </div>

        <div class="content markdown-body" v-html="renderedContent" />

        <div class="tags">
          <el-tag
            v-for="tag in blog.tags"
            :key="tag"
            size="small"
            effect="plain"
            class="tag"
            @click="handleTagClick(tag)"
          >
            {{ tag }}
          </el-tag>
        </div>

        <!-- 相关文章 -->
        <div class="related-blogs" v-if="relatedBlogs.length">
          <h3>相关文章</h3>
          <ul>
            <li v-for="item in relatedBlogs" :key="item.id">
              <router-link :to="`/blog/${item.id}`">
                {{ item.title }}
              </router-link>
              <span class="time">{{ formatDate(item.createTime) }}</span>
            </li>
          </ul>
        </div>

        <!-- 评论区域 -->
        <div class="comments-section">
          <h3>评论</h3>
          <comment-list
            :comments="comments"
            :loading="commentsLoading"
            @submit="handleCommentSubmit"
          />
        </div>
      </template>

      <el-empty v-else description="文章不存在" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Calendar, User, View } from '@element-plus/icons-vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import { useBlogStore } from '@/stores/blog'
import { useUserStore } from '@/stores/user'
import type { Blog, Comment } from '@/types'
import { formatDate, formatNumber } from '@/utils/format'
import CommentList from '@/components/comment/CommentList.vue'

const route = useRoute()
const router = useRouter()
const blogStore = useBlogStore()
const userStore = useUserStore()

const loading = ref(false)
const commentsLoading = ref(false)
const comments = ref<Comment[]>([])
const relatedBlogs = ref<Blog[]>([])

const blog = computed(() => blogStore.currentBlog)

const renderedContent = computed(() => {
  if (!blog.value?.content) return ''
  return marked(blog.value.content, {
    highlight: (code, lang) => {
      if (lang && hljs.getLanguage(lang)) {
        return hljs.highlight(code, { language: lang }).value
      }
      return hljs.highlightAuto(code).value
    }
  })
})

const fetchBlogData = async () => {
  const id = Number(route.params.id)
  if (isNaN(id)) {
    ElMessage.error('无效的文章ID')
    router.push('/')
    return
  }

  loading.value = true
  try {
    await blogStore.fetchBlogDetail(id)
    if (blog.value) {
      await Promise.all([
        fetchComments(),
        fetchRelatedBlogs()
      ])
    }
  } catch (error) {
    console.error('Failed to fetch blog:', error)
    ElMessage.error('获取文章失败')
  } finally {
    loading.value = false
  }
}

const fetchComments = async () => {
  if (!blog.value) return
  
  commentsLoading.value = true
  try {
    // TODO: 实现评论获取逻辑
    comments.value = []
  } finally {
    commentsLoading.value = false
  }
}

const fetchRelatedBlogs = async () => {
  if (!blog.value) return
  
  try {
    // TODO: 实现相关文章获取逻辑
    relatedBlogs.value = []
  } catch (error) {
    console.error('Failed to fetch related blogs:', error)
  }
}

const handleCommentSubmit = async (content: string) => {
  if (!userStore.currentUser) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  if (!blog.value) return

  try {
    // TODO: 实现评论提交逻辑
    await fetchComments()
    ElMessage.success('评论成功')
  } catch (error) {
    console.error('Failed to submit comment:', error)
    ElMessage.error('评论失败')
  }
}

const handleTagClick = (tag: string) => {
  router.push(`/tag/${tag}`)
}

onMounted(() => {
  fetchBlogData()
})
</script>

<style lang="scss" scoped>
.blog-detail-view {
  .blog-header {
    margin-bottom: 30px;
    
    .title {
      margin: 0 0 15px;
      font-size: 2em;
      line-height: 1.3;
    }
    
    .meta {
      display: flex;
      align-items: center;
      gap: 15px;
      color: #999;
      font-size: 0.9em;
      
      .el-icon {
        margin-right: 4px;
      }
    }
  }
  
  .content {
    margin: 30px 0;
  }
  
  .tags {
    margin: 20px 0;
    
    .tag {
      margin-right: 8px;
      cursor: pointer;
      
      &:hover {
        opacity: 0.8;
      }
    }
  }
  
  .related-blogs {
    margin: 30px 0;
    padding-top: 20px;
    border-top: 1px solid #eee;
    
    h3 {
      margin-bottom: 15px;
    }
    
    ul {
      list-style: none;
      padding: 0;
      
      li {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        
        a {
          color: $text-primary;
          text-decoration: none;
          
          &:hover {
            color: $primary-color;
          }
        }
        
        .time {
          color: #999;
          font-size: 0.9em;
        }
      }
    }
  }
  
  .comments-section {
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #eee;
    
    h3 {
      margin-bottom: 20px;
    }
  }
}
</style> 